﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.ServiceModel;
using System.Data;
using System.IO;
using System.Text;

namespace SalaryChannel.Web
{
    public class ServiceAuthRoot
    {
        protected string EmailSender = System.Configuration.ConfigurationManager.AppSettings["EmailSender"];
        protected string EmailSMTP = System.Configuration.
                     ConfigurationSettings.AppSettings["EmailSMTP"];
        protected string EmailSenderUser = System.Configuration.
                  ConfigurationSettings.AppSettings["EmailSenderUser"];
        protected string EmailSenderPwd = System.Configuration.
                  ConfigurationSettings.AppSettings["EmailSenderPwd"];
        protected string EmailReceivers = System.Configuration.
                  ConfigurationSettings.AppSettings["EmailReceivers"];
        protected string SqlString = System.Configuration.ConfigurationManager.ConnectionStrings["SalaryQueryConnectionString"].ConnectionString;
        protected string AMSqlString = System.Configuration.ConfigurationManager.ConnectionStrings["JFAMConnectionString"].ConnectionString;

        protected void Authoricate()
        {
            int indexUser = OperationContext.Current.IncomingMessageHeaders.FindHeader("uafcztga", "");//获取节点user的索引值           
            if (indexUser < 0)
            {
                throw new Exception("非法的请求:未提供User节点");
            }
            string UserStr = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(indexUser);//返回user节点值
            int indexPwd = OperationContext.Current.IncomingMessageHeaders.FindHeader("xufasft", "");

            if (indexPwd < 0)
            {
                throw new Exception("非法的请求:未提供Password节点");
            }
            string PwdStr = OperationContext.Current.IncomingMessageHeaders.GetHeader<string>(indexPwd);
            if (string.IsNullOrEmpty(UserStr)
                || string.IsNullOrEmpty(PwdStr)
                || UserStr != "yangch_ts"
                || PwdStr != "sc.yc.cobs")
            {
                throw new Exception("非法的请求，口令不正确");
            }

        }

        protected string DataTable2Xml(DataTable table)
        {
            if (table == null)
            {
                throw new ArgumentNullException("table");
            }
            if (string.IsNullOrEmpty(table.TableName))
            {
                table.TableName = Guid.NewGuid().ToString();
            }
            string xml = string.Empty;
            using (MemoryStream ms = new MemoryStream())
            {

                try
                {
                    table.WriteXml(ms);
                    byte[] buffer = new byte[ms.Length];
                    ms.Read(buffer, 0, buffer.Length);
                    xml = Encoding.UTF8.GetString(ms.ToArray());
                }
                catch (Exception ex)
                {

                    throw new Exception("序列化失败，" + ex.Message);
                }
            }
            return xml;
        }

        protected string WriteTableIntoFile(DataTable table, string FileNamePrefix)
        {
            if (table.Rows.Count == 0)
            {
                return string.Empty;
            }
            string filename = "Profile/" + FileNamePrefix + "_" +DateTime.Now.Year.ToString()+DateTime.Now.Month.ToString()
                +DateTime.Now.Day.ToString()
                + DateTime.Now.ToShortTimeString().Replace(":", "")+DateTime.Now.Ticks.ToString() + ".csv";
            TextWriter textWriter = new StreamWriter(System.Web.HttpContext.Current.Server.MapPath(filename), false, Encoding.Default);
            string header = string.Empty;
            foreach (System.Data.DataColumn col in table.Columns)
            {
                header += string.Format("\"{0}\",", col.ColumnName);
            }
            header = header.Remove(header.Length - 1);
            textWriter.WriteLine(header);
            foreach (System.Data.DataRow row in table.Rows)
            {
                string line = string.Empty;
                foreach (System.Data.DataColumn col in table.Columns)
                {
                    line += string.Format("\"{0}\",", row[col].ToString());
                }
                line = line.Remove(line.Length - 1);
                textWriter.WriteLine(line);
            }
            textWriter.Close();
            textWriter.Dispose();
            return filename;
        }

        /// <summary>
        /// 通过Web Service发送邮件
        /// </summary>
        /// <param name="Title"></param>
        /// <param name="Msg"></param>
        /// <param name="Receivers"></param>
        protected void SendEmail(string Title, string Msg, string Receivers)
        {
            try
            {
                string EResult = EmailHelper.Email.SendEmail("渠道综合支撑系统",
                              EmailSender,
                              EmailSMTP,
                              EmailSenderUser,
                              EmailSenderPwd,
                              Receivers,
                              Title,
                              Msg,
                              null,
                              "gb2312",
                              false);
                if (!string.IsNullOrEmpty(EResult))
                {
                    LogManager.Write("发送邮件失败," + EResult +
               "--" + System.Web.HttpContext.Current.Request.UserHostAddress);
                }
            }
            catch (Exception ex)
            {

                LogManager.Write("发送邮件失败," + ex.Message +
                "--" + System.Web.HttpContext.Current.Request.UserHostAddress);
            }


        }
        //protected bool SendAMMsg()
        //{
        //    return true;
        //}

        /// <summary>
        /// 直接发送邮件
        /// </summary>
        /// <param name="Title"></param>
        /// <param name="Msg"></param>
        /// <param name="Receivers"></param>
        protected bool SendEmailDirectly(string Title, string Msg, string Receivers)
        {
            try
            {
                Email.SendEmail("卖场销售管理系统",
                               EmailSender,
                               EmailSMTP,
                               EmailSenderUser,
                               EmailSenderPwd,
                               Receivers,
                               Title,
                               Msg,
                               null,
                               "gb2312");
                return true;
            }
            catch (Exception ex)
            {

                LogManager.Write("发送邮件失败," + ex.Message +
                "--" + System.Web.HttpContext.Current.Request.UserHostAddress);
                return false;
            }
        }
    }

}
